package com.legal.aid.app.service.impl;

import com.legal.aid.app.domain.vo.ChatMessage;
import com.legal.aid.app.domain.vo.ChatListVO;
import com.legal.aid.app.domain.vo.CommonUserVo;
import com.legal.aid.app.mapper.ChatMessageMapper;
import com.legal.aid.app.service.ChatMessageService;
import com.legal.aid.app.service.IAppUserService;
import com.legal.aid.common.constant.CacheConstants;
import com.legal.aid.common.core.redis.RedisCache;
import com.legal.aid.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ChatMessageServiceImpl implements ChatMessageService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;
    //
    // @Override
    // public void saveMessage(ChatMessage message) {
    // chatMessageMapper.insert(message);
    // }
    //
    // @Override
    // public List<ChatMessage> getChatHistory(String userId, String lawyerId, int
    // pageSize, int offset) {
    // return chatMessageMapper.getChatHistory(userId, lawyerId, pageSize, offset);
    // }
    //
    // @Override
    // public List<ChatListVO> getChatList(String userId) {
    // return chatMessageMapper.getChatList(userId);
    // }
    //
    // @Override
    // public void updateMessagesToRead(Long sendId, Long receiverId) {
    // chatMessageMapper.updateMessagesToRead(sendId, receiverId);
    // }

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IAppUserService appUserService;

    @Override
    public void saveMessage(ChatMessage message) {
        // 生成唯一消息ID
        if (message.getId() == null) {
            message.setId(generateMessageId());
        }

        // 设置消息时间戳
        if (message.getSendTime() == null) {
            message.setSendTime(new Date());
        }

        // 记录已持久化的消息ID
        // markMessageAsPersisted(message.getId());

        // 生成会话ID（用户ID和律师ID排序后拼接）
        String conversationId = generateConversationId(message.getSenderId(), message.getReceiverId());

        // 保存消息到历史记录（使用List结构，最新消息在最前面）
        String historyKey = CacheConstants.CHAT_HISTORY_KEY + conversationId;
        redisCache.setCacheObject(historyKey + ":msg:" + message.getId(), message,
                (int) CacheConstants.HISTORY_EXPIRE_TIME, CacheConstants.HISTORY_EXPIRE_UNIT);

        // 将消息ID添加到会话的消息列表中
        redisCache.setCacheList(historyKey, Collections.singletonList(message.getId()));

        // 如果是新消息，未读
        if (message.getStatus() == null || message.getStatus() == "0") {
            message.setStatus("0");
            incrementUnreadCount(message.getReceiverId(), message.getSenderId());
        }

        // 更新双方的聊天列表
        updateChatList(message.getSenderId(), message.getReceiverId(), message);
        updateChatList(message.getReceiverId(), message.getSenderId(), message);
        // ：写入数据库
        chatMessageMapper.insert(message);
    }

    @Override
    public List<ChatMessage> getChatHistory(String userId, String lawyerId, int pageSize, int offset) {
        String conversationId = generateConversationId(userId, lawyerId);
        String historyKey = CacheConstants.CHAT_HISTORY_KEY + conversationId;

        // 获取消息ID列表（倒序排列，最新的在前）
        List<Long> messageIds = redisCache.getCacheList(historyKey);

        // 分页处理
        int startIndex = Math.max(0, messageIds.size() - offset - pageSize);
        int endIndex = Math.max(0, messageIds.size() - offset);
        if (startIndex >= endIndex) {
            return Collections.emptyList();
        }

        List<ChatMessage> messages = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            Long messageId = messageIds.get(i);
            ChatMessage message = redisCache.getCacheObject(historyKey + ":msg:" + messageId);
            if (message != null) {
                messages.add(message);
            }
        }

        // 按时间正序排列
        Collections.sort(messages, Comparator.comparing(ChatMessage::getSendTime));

        return messages;
    }

    // @Override
    // public List<ChatListVO> getChatList(String userId) {
    // String chatListKey = CacheConstants.CHAT_LIST_KEY + userId;
    // List<String> partnerIds = redisCache.getCacheList(chatListKey);
    //
    // List<ChatListVO> chatList = new ArrayList<>();
    // for (String partnerId : partnerIds) {
    // ChatListVO chatItem = new ChatListVO();
    // chatItem.setPartnerId(partnerId);
    //
    // // 获取最新消息
    // String conversationId = generateConversationId(userId, partnerId);
    // String historyKey = CacheConstants.CHAT_HISTORY_KEY + conversationId;
    // List<Long> messageIds = redisCache.getCacheList(historyKey);
    // if (!messageIds.isEmpty()) {
    // Long latestMessageId = messageIds.get(messageIds.size()-1);
    // ChatMessage latestMessage = redisCache.getCacheObject(historyKey + ":msg:" +
    // latestMessageId);
    // if (latestMessage != null) {
    // chatItem.setLastMessage(latestMessage.getContent());
    // chatItem.setSendTime(latestMessage.getSendTime());
    // // 获取聊天对象的avatar 和userName 拼接到ChatListVO
    // appUserService.getByUserId()
    // chatItem.setAvatar();
    // }
    // }
    //
    // // 获取未读消息数
    // chatItem.setUnreadCount(getUnreadCount(userId, partnerId));
    //
    // chatList.add(chatItem);
    // }
    //
    // return chatList;
    // }

    // @Override
    // public List<ChatMessage> getlawyerMessages(String lawyerId) {
    // return chatMessageMapper.getlawyerMessages(lawyerId);
    // }

    @Override
    public List<ChatListVO> getChatList(String userId) {
        String chatListKey = CacheConstants.CHAT_LIST_KEY + userId;
        List<String> partnerIds = redisCache.getCacheList(chatListKey);

        if (partnerIds == null || partnerIds.isEmpty()) {
            return Collections.emptyList();
        }

        List<ChatListVO> chatList = new ArrayList<>();

        // 优化：批量查询用户信息，减少数据库查询次数
        Set<Long> partnerIdSet = new HashSet<>();
        for (String partnerId : partnerIds) {
            try {
                partnerIdSet.add(Long.parseLong(partnerId));
            } catch (NumberFormatException e) {
                throw new ServiceException("获取用户列表失败");
            }
        }

        // 假设 appUserService 有批量查询用户信息的方法
        Map<Long, CommonUserVo> userMap = appUserService.listByIds(new ArrayList<>(partnerIdSet));

        for (String partnerId : partnerIds) {
            ChatListVO chatItem = new ChatListVO();
            chatItem.setPartnerId(partnerId);

            try {
                Long partnerIdLong = Long.parseLong(partnerId);
                CommonUserVo partnerUser = userMap.get(partnerIdLong);

                if (partnerUser != null) {
                    chatItem.setUserId(partnerIdLong);
                    chatItem.setUserName(partnerUser.getUserName());
                    chatItem.setAvatar(partnerUser.getAvatar());
                }
            } catch (NumberFormatException e) {
                throw new ServiceException("获取用户列表失败");
            }

            // 获取最新消息
            String conversationId = generateConversationId(userId, partnerId);
            String historyKey = CacheConstants.CHAT_HISTORY_KEY + conversationId;
            List<Long> messageIds = redisCache.getCacheList(historyKey);

            if (!messageIds.isEmpty()) {
                // 取最后一个元素（最早的消息ID？需要确认列表顺序）
                // 注意：如果消息ID列表是按最新到最旧排列，应该最后一个元素
                Long latestMessageId = messageIds.get(messageIds.size() - 1);
                ChatMessage latestMessage = redisCache.getCacheObject(historyKey + ":msg:" + latestMessageId);

                if (latestMessage != null) {
                    chatItem.setLastMessage(latestMessage.getContent());
                    chatItem.setSendTime(latestMessage.getSendTime());
                }
            }

            // 获取未读消息数
            chatItem.setUnreadCount(getUnreadCount(userId, partnerId));
            chatList.add(chatItem);
        }

        return chatList;
    }

    @Override
    public void updateMessagesToRead(Long senderId, Long receiverId) {
        // 先更新数据库
        chatMessageMapper.updateMessagesToRead(senderId, receiverId);

        // 再清除Redis缓存
        String unreadKey = CacheConstants.UNREAD_COUNT_KEY + receiverId + ":" + senderId;
        redisCache.deleteObject(unreadKey);
    }

    @Override
    public void deleteMessage(Long messageId) {
        // 1. 先查出消息内容（为了拿到senderId/receiverId）
        ChatMessage msg = chatMessageMapper.selectById(messageId);
        if (msg == null) {
            throw new ServiceException("消息不存在");
        }

        // 2. 删除数据库记录
        chatMessageMapper.deleteMessageById(messageId);

        // 3. 删除Redis缓存
        String conversationId = generateConversationId(msg.getSenderId(), msg.getReceiverId());
        String historyKey = CacheConstants.CHAT_HISTORY_KEY + conversationId;
        // 删除消息内容缓存
        redisCache.deleteObject(historyKey + ":msg:" + messageId);
        // 从消息ID列表中移除
        redisCache.removeFromList(historyKey, 0, messageId);
    }

    // 生成唯一消息ID
    private synchronized Long generateMessageId() {
        return redisCache.increment(CacheConstants.MESSAGE_ID_KEY, 1);
    }

    // 生成会话ID（确保相同两人的会话ID相同）
    private String generateConversationId(String userId1, String userId2) {
        return userId1.compareTo(userId2) < 0
                ? userId1 + "_" + userId2
                : userId2 + "_" + userId1;
    }

    // 增加未读消息计数
    private void incrementUnreadCount(String receiverId, String senderId) {
        String unreadKey = CacheConstants.UNREAD_COUNT_KEY + receiverId + ":" + senderId;
        redisCache.increment(unreadKey, 1);
    }

    // 获取未读消息计数
    private Integer getUnreadCount(String receiverId, String senderId) {
        String unreadKey = CacheConstants.UNREAD_COUNT_KEY + receiverId + ":" + senderId;
        Long count = redisCache.getCount(unreadKey);
        return count != null ? count.intValue() : 0;
    }

    // 更新用户的聊天列表
    // private void updateChatList(String userId, String partnerId, ChatMessage
    // message) {
    // String chatListKey = CacheConstants.CHAT_LIST_KEY + userId;
    //
    // // 先移除已存在的对方ID（如果有）
    // List<String> partnerIds = redisCache.getCacheList(chatListKey);
    // if (partnerIds.contains(partnerId)) {
    // partnerIds.remove(partnerId);
    // redisCache.deleteObject(chatListKey);
    // redisCache.setCacheList(chatListKey, partnerIds);
    // }
    //
    // // 将对方ID添加到列表最前面（表示最新会话）
    // redisCache.setCacheList(chatListKey, Collections.singletonList(partnerId));
    // }

    private void updateChatList(String userId, String partnerId, ChatMessage message) {
        String chatListKey = CacheConstants.CHAT_LIST_KEY + userId;

        // 1. 先移除已存在的对方ID（如果有）
        redisCache.removeFromList(chatListKey, 0, partnerId); // 移除所有匹配的元素

        // 2. 使用 LPUSH 将对方ID添加到列表头部
        redisCache.leftPush(chatListKey, partnerId);
    }

    // // 标记消息为已持久化
    // private void markMessageAsPersisted(Long messageId) {
    // String persistedKey = CacheConstants.PERSISTED_MESSAGES_KEY + messageId;
    // redisCache.setCacheObject(persistedKey, "1", 48, TimeUnit.HOURS);
    // }

}